package com.example.finalproject.User;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String index(){
        return "index";
    }

    //在首页点击登录跳转页面并创建空对象给前端
    @RequestMapping("/pre_login")
    public String pre_login(Model model){
        User user = new User();
        model.addAttribute("user",user);
        return "login";
    }
    /**注册页面请求,点击注册账号按钮
    @RequestMapping("/register")
    public void pre_register(Model model){
        //创建空对象接收前端数据
        User user = new User();
        model.addAttribute("user",user);

    }
    **/
    //点击《注册账号》按钮
    @RequestMapping("/addUser")
    public String register(@Validated @ModelAttribute("user")  User user, BindingResult rs/*保存验证结果信息*/, Model model){

        //@ModelAttribute("user")与th:object="${user}"相对应
        if(rs.hasErrors()){//验证失败
            return "login";
        }

        // 检查用户是否已存在于数据库中
        User existingUser = userService.selectUserByName(user.getUserName());
        if(existingUser != null) {
            model.addAttribute("messageInfo", "用户已存在!");
            return "login";
        }

        //不存在，添加新用户
        userService.insertUser(user);
        model.addAttribute("messageInfo","注册成功!");
        return "login";
    }

    //点击《立即登录》，按钮登录检查用户名密码是否正确
    @RequestMapping("/login")
    public String login(String userName, String userPassWord, Model model, HttpServletRequest request){
        User existingUser = userService.selectUserByName(userName);
        if(existingUser != null){
            if(existingUser.getUserPassWord().equals(userPassWord)){
                //登录成功返回到首页
                //保存一个登录成功的用户名
                HttpSession session = request.getSession();
                session.setAttribute("login_User",existingUser);
                System.out.println("登录成功");
                return "index";
            }
        }
        System.out.println("登录失败");
        model.addAttribute("messageInfo","用户名或密码输入错误!");
        return "login";
    }

}
